import api from '../../api/index'
import * as types from '../mutation-types';

const state = {
  demosList: [],
  demosPerson: [],
  personDemo: [],

  demoDetail: {},

  demosTotal: 0,
  demoSelect: [],

  demoScrollTop: 0
}

const actions = {
  getDemosList({
    commit
  }, params) {
    api.get_demos_list(params).then(res => {
      commit(types.GET_DEMOS_LIST, res)
    })
  },
  getDemosPerson({
    commit
  }, params) {
    api.get_demos_person(params).then(res => {
      commit(types.GET_DEMOS_PERSON, res)
    })
  },
  getPersonDemo({
    commit
  }, params) {
    api.get_person_demo(params).then(res => {
      commit(types.GET_PERSON_DEMO, res)
    })
  },
  getDemoDetail({
    commit
  }, params) {
    api.get_demo_detail(params).then(res => {
      commit(types.GET_DEMO_DETAIL, res)
    })
  },
  getDemoSelect({
    commit
  }, params) {
    api.get_demos_select(params).then(res => {
      commit(types.GET_DEMOS_SELECT, res)
    })
  },

  updateDemosPosition({
    commit
  }, top) {
    commit({
      type: 'updateDemosPosition',
      top: top
    })
  }
}

const getters = {
  demosList: state => state.demosList,
  demosPerson: state => state.demosPerson,
  personDemo: state => state.personDemo,
  demoDetail: state => state.demoDetail,

  demosTotal: state => state.demosTotal,
  demoSelect: state => state.demoSelect,
  demoScrollTop: state => state.demoScrollTop
}

const mutations = {
  [types.GET_DEMOS_LIST](state, res) {
    if (res.code === 0) {
      state.demosList = []
      state.demosTotal = 0
    } else {
      if (res.data.data.length !== 0 && res.data.current_page !== 1) {
        let end = res.data.current_page * 10
        let start = end - 10
        for (start; start < end; start++) {
          if (start < res.data.total) {
            let newIndex = start % 10;
            state.demosList.push(res.data.data[newIndex])
          }
        }
      } else if (res.data.current_page == 1 && res.data.data.length !== 0) {
        state.demosList = res.data.data
        state.demosTotal = res.data.total
      }
    }
  },
  [types.GET_DEMOS_PERSON](state, res) {
    if (res.code === 0) {
      state.demosPerson = []
    } else {
      state.demosPerson = res.data
    }
  },
  [types.GET_PERSON_DEMO](state, res) {
    if (res.code === 0) {
      state.personDemo = []
    } else {
      state.personDemo = res.data
    }
  },
  [types.GET_DEMO_DETAIL](state, res) {
    if (res.code === 0) {
      state.demoDetail = {}
    } else {
      state.demoDetail = res.data
    }
  },
  [types.GET_DEMOS_SELECT](state, res) {
    if (res.code === 0) {
      state.demoSelect = []
    }else {
      state.demoSelect = res.data
    }
  },

  updateDemosPosition(state, payload) {
    state.demoScrollTop = payload.top
  }
}

export default {
  state,
  actions,
  getters,
  mutations,
}
